package com.gmall.rabbitmq.producer.service;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Service
public class ReliableMQService {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init(){
        //消息发送到交换机，会调用ConfirmCallback
        rabbitTemplate.setConfirmCallback((CorrelationData correlationData,
                                           boolean ack,
                                           String cause)->{
            if(ack){
                //MQ 收到消息，从mysql/redis 删除
                System.out.println("---->" + correlationData.getId());
            }
            //只要交换机收到，就会打算Confirm
            System.out.println("Confirm :  correlationData:"
                    +correlationData+",ack:"+ack+",cause:"+cause);
        });
        //消息发送到交换机，但是没有正确路由到队列,会调用returnCallback
        rabbitTemplate.setReturnCallback((Message message,
                                          int replyCode,
                                          String replyText,
                                          String exchange,
                                          String routingKey)->{
            System.out.println("Return :  message:"+message+"," +
                    "replyCode:"+replyCode+"," +
                    "replyText:"+replyText+"," +
                    "exchange:"+exchange+"," +
                    "routingKey:"+routingKey);
        });
    }
}
